import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:flutter_ui/services/auth_service.dart';

// 全局导航键，用于在任何地方导航而不需要context
final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();

/// 导航到登录页面
/// 
/// 在401未授权错误时调用，使用全局导航器跳转到登录页面
void navigateToLogin() {
  navigatorKey.currentState?.pushNamedAndRemoveUntil('/login', (route) => false);
}

/// HTTP服务
/// 
/// 封装HTTP请求，处理请求拦截、响应拦截和错误处理
/// 自动处理401未授权错误，实现Token刷新和重试机制
class HttpService {
  // 单例实例
  static final HttpService _instance = HttpService._internal();
  
  // 工厂构造函数
  factory HttpService() => _instance;
  
  // 内部构造函数
  HttpService._internal();
  
  // 认证服务实例
  final AuthService _authService = AuthService();
  
  // API基础URL
  final String _baseUrl = 'https://api.example.com'; // 实际项目中替换为真实API地址
  
  /// 发送GET请求
  /// 
  /// [endpoint] API端点
  /// [queryParams] 查询参数
  /// [requiresAuth] 是否需要认证
  Future<Map<String, dynamic>> get(String endpoint, {
    Map<String, dynamic>? queryParams,
    bool requiresAuth = true,
  }) async {
    return _sendRequest(
      'GET',
      endpoint,
      queryParams: queryParams,
      requiresAuth: requiresAuth,
    );
  }
  
  /// 发送POST请求
  /// 
  /// [endpoint] API端点
  /// [body] 请求体
  /// [requiresAuth] 是否需要认证
  Future<Map<String, dynamic>> post(String endpoint, {
    Map<String, dynamic>? body,
    bool requiresAuth = true,
  }) async {
    return _sendRequest(
      'POST',
      endpoint,
      body: body,
      requiresAuth: requiresAuth,
    );
  }
  
  /// 发送PUT请求
  /// 
  /// [endpoint] API端点
  /// [body] 请求体
  /// [requiresAuth] 是否需要认证
  Future<Map<String, dynamic>> put(String endpoint, {
    Map<String, dynamic>? body,
    bool requiresAuth = true,
  }) async {
    return _sendRequest(
      'PUT',
      endpoint,
      body: body,
      requiresAuth: requiresAuth,
    );
  }
  
  /// 发送DELETE请求
  /// 
  /// [endpoint] API端点
  /// [requiresAuth] 是否需要认证
  Future<Map<String, dynamic>> delete(String endpoint, {
    bool requiresAuth = true,
  }) async {
    return _sendRequest(
      'DELETE',
      endpoint,
      requiresAuth: requiresAuth,
    );
  }
  
  /// 发送HTTP请求
  /// 
  /// [method] HTTP方法
  /// [endpoint] API端点
  /// [body] 请求体
  /// [queryParams] 查询参数
  /// [requiresAuth] 是否需要认证
  Future<Map<String, dynamic>> _sendRequest(
    String method,
    String endpoint, {
    Map<String, dynamic>? body,
    Map<String, dynamic>? queryParams,
    bool requiresAuth = true,
  }) async {
    try {
      // 构建完整URL
      var uri = Uri.parse('$_baseUrl/$endpoint');
      if (queryParams != null) {
        uri = uri.replace(queryParameters: queryParams.map((key, value) => MapEntry(key, value.toString())));
      }
      
      // 准备请求头
      final headers = <String, String>{
        'Content-Type': 'application/json',
        'Accept': 'application/json',
      };
      
      // 如果需要认证，添加Authorization头
      if (requiresAuth) {
        final token = _authService.token;
        if (token == null) {
          throw Exception('未登录，无法访问需要认证的API');
        }
        headers['Authorization'] = 'Bearer $token';
      }
      
      // 发送请求
      http.Response response;
      switch (method) {
        case 'GET':
          response = await http.get(uri, headers: headers);
          break;
        case 'POST':
          response = await http.post(
            uri,
            headers: headers,
            body: body != null ? jsonEncode(body) : null,
          );
          break;
        case 'PUT':
          response = await http.put(
            uri,
            headers: headers,
            body: body != null ? jsonEncode(body) : null,
          );
          break;
        case 'DELETE':
          response = await http.delete(uri, headers: headers);
          break;
        default:
          throw Exception('不支持的HTTP方法: $method');
      }
      
      // 处理响应
      return _handleResponse(response);
    } catch (e) {
      debugPrint('HTTP请求错误: $e');
      rethrow;
    }
  }
  
  /// 处理HTTP响应
  /// 
  /// [response] HTTP响应
  /// 处理常见HTTP错误，特别是401未授权错误
  Future<Map<String, dynamic>> _handleResponse(http.Response response) async {
    final statusCode = response.statusCode;
    final responseBody = response.body.isNotEmpty ? jsonDecode(response.body) : {};
    
    if (statusCode >= 200 && statusCode < 300) {
      // 请求成功
      return responseBody as Map<String, dynamic>;
    } else if (statusCode == 401) {
      // 未授权，可能是Token过期
      await _authService.handleUnauthorized();
      // 使用全局导航器跳转到登录页面
      navigateToLogin();
      throw Exception('登录已过期，请重新登录');
    } else if (statusCode == 403) {
      // 禁止访问
      throw Exception('没有权限访问该资源');
    } else if (statusCode == 404) {
      // 资源不存在
      throw Exception('请求的资源不存在');
    } else if (statusCode >= 500) {
      // 服务器错误
      throw Exception('服务器错误，请稍后再试');
    } else {
      // 其他错误
      final message = responseBody['message'] ?? '未知错误';
      throw Exception('请求失败: $message');
    }
  }
}